const STORAGE_KEYS = require("../../configs/STORAGE_KEYS");
const playersStore = require('../../stores/players');
const recordsStore = require('../../stores/records');

// pages/start/start.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    east: null,
    south: null,
    west: null,
    north: null,
    currentPos: undefined,
    /** 是否有未结束的牌局 */
    hasLeftRound: false,
  },

  onShow() {
    // 如果有未结束的牌局，则会读取上一局数据
    // 读取并设置上一局的参赛人员信息
    const currentPlayers = playersStore.getCurrentPlayers()
    const currentStartTime = wx.getStorageSync(STORAGE_KEYS.CURRENT_START_TIME)
    if (Array.isArray(currentPlayers) && currentPlayers.length === 4) {
      const [east, south, west, north] = currentPlayers;
      this.setData({ east, south, west, north, hasLeftRound: !!currentStartTime })
    }
  },

  handleStartChoose(event) {
    this.setData({ show: true, currentPos: event.detail })
  },

  handleChoose(event) {
    const currentPos = this.data.currentPos;
    const player = event.detail;
    const { east, south, west, north } = this.data;
    if ([east, south, west, north].some(p => p && p.playerNum === player.playerNum)) {
      wx.showToast({
        title: player.nickname + '已被选择，请查看',
        icon: 'none',
      })
      return;
    }
    this.setData({ show: false, [currentPos]: event.detail })
  },

  validate() {
    const { east, south, west, north } = this.data
    const nonSelectIndex = [east, south, west, north].indexOf(null);
    let message;
    // 要全部选择才行
    if (nonSelectIndex > -1) {
      message = `请选择${'东南西北'[nonSelectIndex]}位置人员`
    }
    if (message) {
      wx.showToast({
        title: message,
        icon: 'none',
      })
      return false;
    }
    return true;
  },

  handleStart() {
    const validateRes = this.validate()
    if (validateRes) {
      const { east, south, west, north } = this.data
      const playerNums = [east, south, west, north].map(item => item.playerNum)
      wx.setStorageSync(STORAGE_KEYS.CURRENT_PLAYER_NUMS, playerNums)
      wx.setStorageSync(STORAGE_KEYS.CURRENT_START_TIME, Date.now())
      wx.navigateTo({
        url: `/pages/game/game`,
      })
    }
  },

  // 继续对局中，支持修改参赛人员
  handleContinue() {
    const validateRes = this.validate();
    if(validateRes) {
      const { east, south, west, north } = this.data
      const playerNums = [east, south, west, north].map(item => item.playerNum)
      wx.setStorageSync(STORAGE_KEYS.CURRENT_PLAYER_NUMS, playerNums)
      wx.navigateTo({
        url: `/pages/game/game`,
      })
    }
  },

  handleClose() {
    this.setData({ show: false })
  },

  handleGiveup() {
    wx.showModal({
      title: '提示',
      content: '放弃当前记录后将无法复原，请确认！',
      complete: (res) => {
        if (res.confirm) {
          recordsStore.clearCurrent();
          this.setData({
            east: null,
            south: null,
            west: null,
            north: null,
            hasLeftRound: false,
          })
        }
      }
    })
  }
})